from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from .bootstrap import BootStrapModelForm
from django import forms
from app01 import models


class UserModelForm(BootStrapModelForm):
    name = forms.CharField(min_length=3, label='用户名')

    class Meta:
        model = models.UserInfo
        fields = ['name', 'password', 'age', 'account', 'creat_time', 'gender', 'depart']


class PrettyModelFrom(BootStrapModelForm):
    # 验证方式1: 字段+正则
    mobile = forms.CharField(
        label='手机号',
        # 添加格式校验
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'), ],
    )

    class Meta:
        model = models.PrettyNum
        # 指定字段
        fields = ['mobile', 'price', 'level', 'status']
        # 所有字段
        # fields = '__all__'
        # 排除字段
        # exclude = ['id']

    # 验证方式2: 钩子方法
    def clean_mobile(self):
        txt_mobile = self.cleaned_data['mobile']

        if models.PrettyNum.objects.filter(mobile=txt_mobile).exists():
            raise ValidationError('手机号已存在!')
        if len(txt_mobile) != 11:
            # 验证不通过
            raise ValidationError('格式错误!')
        # 验证通过, 则返回用户输入的值
        return txt_mobile


class PrettyEditModelFrom(BootStrapModelForm):
    # 验证方式1: 字段+正则
    mobile = forms.CharField(
        label='手机号',
        # 添加格式校验
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'), ],
    )

    class Meta:
        model = models.PrettyNum
        # 指定字段
        fields = ['mobile', 'price', 'level', 'status']

    # 验证方式2: 钩子方法
    def clean_mobile(self):
        # 当前编辑那行的ID
        # self.instance.pk

        txt_mobile = self.cleaned_data['mobile']

        # id != 自身 and mobile 不重复
        if models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists():
            raise ValidationError('手机号已存在!')
        if len(txt_mobile) != 11:
            # 验证不通过
            raise ValidationError('格式错误!')
        # 验证通过, 则返回用户输入的值
        return txt_mobile
